package com.alan.swagger2.controller;

import com.alan.swagger2.bean.BaseState;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

/**
 * @Auther: Alan liu
 * @Date: 2018/10/31 10:34
 * @Description: Ueditor使用
 */
@Slf4j
@Controller
@RequestMapping("ueditor")
public class UeditorController {

    private JSONObject configAll = null;
    public static final Map<String, Integer> mapping;
    // 获取配置请求
    public static final int CONFIG = 0;
    public static final int UPLOAD_IMAGE = 1;
    public static final int UPLOAD_SCRAWL = 2;
    public static final int UPLOAD_VIDEO = 3;
    public static final int UPLOAD_FILE = 4;
    public static final int CATCH_IMAGE = 5;
    public static final int LIST_FILE = 6;
    public static final int LIST_IMAGE = 7;

    // 涂鸦上传filename定义
    private final static String SCRAWL_FILE_NAME = "scrawl";
    // 远程图片抓取filename定义
    private final static String REMOTE_FILE_NAME = "remote";


    static {
        mapping = new HashMap<String, Integer>(){{
            put( "config", UeditorController.CONFIG );
            put( "uploadimage", UeditorController.UPLOAD_IMAGE );
            put( "uploadscrawl", UeditorController.UPLOAD_SCRAWL );
            put( "uploadvideo", UeditorController.UPLOAD_VIDEO );
            put( "uploadfile", UeditorController.UPLOAD_FILE );
            put( "catchimage", UeditorController.CATCH_IMAGE );
            put( "listfile", UeditorController.LIST_FILE );
            put( "listimage", UeditorController.LIST_IMAGE );
        }};
    }



    @ApiIgnore
    @RequestMapping(value = "controller")
    @ResponseBody
    private String controller(HttpServletRequest request){
        String res = "";
        String callbackName = request.getParameter("callback");
        String result = "";
        String actionType = request.getParameter( "action" );
        int actionCode = mapping.get(actionType);
        BaseState state = null;
        Map<String, Object> conf = null;
        switch ( actionCode ) {

            case CONFIG:
                result = getConfigAll();
                break;

            case UPLOAD_IMAGE:
            case UPLOAD_SCRAWL:
            case UPLOAD_VIDEO:
            case UPLOAD_FILE:
                conf = getConfig( actionCode );
                //文件上传
                String suffix = "svg";
                state = new BaseState(true,"OK");
                state.putInfo("url","https://xzlogo.com/static/images/_common/xzlogo_head.svg");
                state.putInfo("type",suffix);
                state.putInfo("original","logo"+suffix);
                result = state.toJSONString();
                break;
            case CATCH_IMAGE:
//                conf = configManager.getConfig( actionCode );
//                String[] list = this.request.getParameterValues( (String)conf.get( "fieldName" ) );
//                state = new ImageHunter( conf ).capture( list );
                break;

            case LIST_IMAGE:
            case LIST_FILE:
//                conf = configManager.getConfig( actionCode );
//                int start = this.getStartIndex();
//                state = new FileManager( conf ).listFile( start );
                break;

        }

        if( callbackName != null){
            res = callbackName+"("+result+");";
        } else {
            res = result;
        }
        return res;
    }


    private String getConfigAll(){
        if(configAll != null){
            return configAll.toJSONString();
        }else {
            initConfig();
        }
        return configAll.toJSONString();
    }

    private String[] getArray ( String key ) {
        JSONArray jsonArray = configAll.getJSONArray( key );
        String[] result = new String[ jsonArray.size() ];
        for ( int i = 0, len = jsonArray.size(); i < len; i++ ) {
            result[i] = jsonArray.getString( i );
        }
        return result;

    }

    private Map<String, Object> getConfig(int type){
        Map<String, Object> conf = new HashMap<>();
        if(configAll == null){
            initConfig();
        }
        String savePath = null;
        switch ( type ) {

            case UPLOAD_FILE:
                conf.put( "isBase64", "false" );
                conf.put( "maxSize", configAll.getLong( "fileMaxSize" ) );
                conf.put( "allowFiles", this.getArray( "fileAllowFiles" ) );
                conf.put( "fieldName", configAll.getString( "fileFieldName" ) );
                savePath = configAll.getString( "filePathFormat" );
                break;

            case UPLOAD_IMAGE:
                conf.put( "isBase64", "false" );
                conf.put( "maxSize", configAll.getLong( "imageMaxSize" ) );
                conf.put( "allowFiles", this.getArray( "imageAllowFiles" ) );
                conf.put( "fieldName", configAll.getString( "imageFieldName" ) );
                savePath = configAll.getString( "imagePathFormat" );
                break;

            case UPLOAD_VIDEO:
                conf.put( "maxSize", configAll.getLong( "videoMaxSize" ) );
                conf.put( "allowFiles", this.getArray( "videoAllowFiles" ) );
                conf.put( "fieldName", configAll.getString( "videoFieldName" ) );
                savePath = configAll.getString( "videoPathFormat" );
                break;

            case UPLOAD_SCRAWL:
                conf.put( "filename", SCRAWL_FILE_NAME );
                conf.put( "maxSize", configAll.getLong( "scrawlMaxSize" ) );
                conf.put( "fieldName", configAll.getString( "scrawlFieldName" ) );
                conf.put( "isBase64", "true" );
                savePath = configAll.getString( "scrawlPathFormat" );
                break;

            case CATCH_IMAGE:
                conf.put( "filename", REMOTE_FILE_NAME );
                conf.put( "filter", this.getArray( "catcherLocalDomain" ) );
                conf.put( "maxSize", configAll.getLong( "catcherMaxSize" ) );
                conf.put( "allowFiles", this.getArray( "catcherAllowFiles" ) );
                conf.put( "fieldName", configAll.getString( "catcherFieldName" ) + "[]" );
                savePath = configAll.getString( "catcherPathFormat" );
                break;

            case LIST_IMAGE:
                conf.put( "allowFiles", this.getArray( "imageManagerAllowFiles" ) );
                conf.put( "dir", configAll.getString( "imageManagerListPath" ) );
                conf.put( "count", configAll.getIntValue( "imageManagerListSize" ) );
                break;

            case LIST_FILE:
                conf.put( "allowFiles", this.getArray( "fileManagerAllowFiles" ) );
                conf.put( "dir", configAll.getString( "fileManagerListPath" ) );
                conf.put( "count", configAll.getIntValue( "fileManagerListSize" ) );
                break;

        }

        conf.put( "savePath", savePath );
        conf.put( "rootPath", "biz/" );

        return conf;
    }

    private synchronized void initConfig(){
        try {
            InputStream is = UeditorController.class.getClassLoader().getResourceAsStream("biz/config.json");
            StringBuilder builder = new StringBuilder();
            BufferedReader bfReader = new BufferedReader( new InputStreamReader(is));
            String tmpContent = null;
            while (null != (tmpContent = bfReader.readLine())) {
                builder.append( tmpContent );
            }
            bfReader.close();
            configAll = JSONObject.parseObject(builder.toString());
        } catch (Exception e){
            log.error("异常：{}",e);
        }
    }




    public static void main(String[] args) {
        System.out.println(UeditorController.class.getClassLoader().getResource(""));
        UeditorController ueditorController = new UeditorController();
        ueditorController.initConfig();
    }


}
